(function( $ ) {
  $.fn.Formula = function() {
  
    var $this = $(this);
    
    var parent = $this.parent();
    
    parent.prepend($('<div>').attr('class', 'leftPanel'));
    var $div = parent.children('.leftPanel');
    
    function agregar ($nombre, $valor ) {
        if($valor==null){
            $div.append($('<button>').attr('class', 'button medium elemento opcion').attr('data', $nombre).text($nombre));
        }else{
            $div.append($('<button>').attr('class', 'button medium elemento opcion').attr('data', $valor).text($nombre));
        }
    }
    
    var arr = [
        '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '+', '-', '*', '/', '(', ')', '[', ']', '{', '}', '<', '>', '<=', '>='
    ];
    
    for (var a in arr){
        agregar(arr[a], null);
    }
    
    $this.addClass('xxlarge');
    parent.append($('<div>').attr('class', 'rightPanel').append($('<div>').attr('class', 'button medium elemento borrar').text('Borrar Formula')));
    
  };
})( jQuery );

jQuery.fn.extend({
    insertAtCaret: function(myValue){
      return this.each(function(i) {
        if (document.selection) {
          //For browsers like Internet Explorer
          this.focus();
          sel = document.selection.createRange();
          sel.text = myValue;
          this.focus();
        }
        else if (this.selectionStart || this.selectionStart == '0') {
          //For browsers like Firefox and Webkit based
          var startPos = this.selectionStart;
          var endPos = this.selectionEnd;
          var scrollTop = this.scrollTop;
          this.value = this.value.substring(0, startPos)+myValue+this.value.substring(endPos,this.value.length);
          this.focus();
          this.selectionStart = startPos + myValue.length;
          this.selectionEnd = startPos + myValue.length;
          this.scrollTop = scrollTop;
        } else {
          this.value += myValue;
          this.focus();
        }
      })
    }
});

$(document).ready(function(){ 
  
    function agregar(textoNuevo){
        $('textarea.formula').insertAtCaret(textoNuevo);
    }
    
    $( ".formula" ).Formula();

    $(".opcion").live("click", function(){
        agregar($(this).attr('data'));
        return false;
    });
    
    $(".borrar").live("click", function(){
        $(this).parent().parent().find('textarea').val("");
        return false;
    });
    
    $(".fila").live("click", function(){
        var fila = $(this);
        var id = fila.parent().parent().attr('id');
        agregar(' _'+id+'('+fila.children('.id').text()+') ');
    });
    
    $(".funcion").live("click", function(){
        var fila = $(this);
        agregar(' ' + fila.children(":eq(1)").text() + ' ');
    });
    
});